package concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description
 * @Author zhangxiaojun
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/4/24
 */
public class DefaultThreadFactory implements ThreadFactory {
    static final AtomicLong poolNumber = new AtomicLong(1L);
    final ThreadGroup group;
    final AtomicLong threadNumber = new AtomicLong(1L);
    final String namePrefix;

    public DefaultThreadFactory() {
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = String.format("fp-pool-%s-thread-", poolNumber.getAndIncrement() );
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(group, runnable,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        return thread;
    }
}
